<?php
/**
 *User.php    当前文件名
 *Administrator         当前用户
 *15:46         系统时间
 *yydati 工程名
 *PhpStorm IDE名称
 **/

namespace app\api\controller;


use app\BaseController;
use think\facade\Db;
use think\facade\Validate;

class Prescription extends BaseController
{
    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取处方列表
     */
    public function getPrescription()
    {
        $topicIds = Db::name('topic_data')
            ->where('status', 1)
            ->where('mark', 1)
            ->where('type', 2)
            ->column('id');
        $prescriptionList = Db::name('prescription')
            ->whereIn('topic_id', $topicIds)
            ->where('status', 1)
            ->where('mark', 1)
            ->withoutField('status,create_time,mark,update_time,topic_id,sort')
            ->select()
            ->toArray();
        return message("操作成功", true, $prescriptionList);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取处方题库
     */
    public function getPrescriptionProblem()
    {
        $params = input('post.');
        $trainp = Db::name('train_problem')
            ->where('prescription_id', $params['prescription_id'])
            ->where('status', 1)
            ->where('mark', 1)
            ->field('id,title,score,prescription_id,right_key')
            ->select()
            ->toArray();
            shuffle($trainp);
//        1 随机 2 固定 出题顺序
//        if ($exam_info['is_rand'] == 1) {
//            shuffle($examp);
//        }

        $problemIds = array_column($trainp, 'id');
        $prescriptionIds = array_column($trainp, 'prescription_id');
        $prescriptionInfo = Db::name('prescription')
            ->whereIn('id', $prescriptionIds)
            ->field('id,title,problem_img')
            ->select()
            ->toArray();
        $answerInfo = Db::name('answer')
            ->whereIn('problem_id', $problemIds)
            ->where('type', 1)
            ->withoutField('create_time,status,update_time,type')
            ->select()
            ->toArray();
        foreach ($trainp as &$prob) {
            $prob['prescription_name'] = '';
            $prob['problem_img'] = '';
            $prob['ans'] = [];
            foreach ($prescriptionInfo as $prescriptionItem) {
                if ($prob['prescription_id'] == $prescriptionItem['id']) {
                    $prob['prescription_name'] = $prescriptionItem['title'];
                    $prob['problem_img'] = $prescriptionItem['problem_img'];
                }
            }
            foreach ($answerInfo as $ans) {
                if ($prob['id'] == $ans['problem_id']) {
                    unset($ans['problem_id'], $ans['id']);
                    $prob['ans'][] = $ans;
                }
            }
        }
        $examp = array_reduce($trainp, function ($result, $item) {
            // 获取当前项的年龄值作为分组依据
            $key = $item['prescription_name'];

            if (!isset($result[$key])) {
                // 如果该年龄还没有被分组过，则创建新的分组并将其添加到结果集合中
                $result[$key] = [];
            }
            // 将当前项添加到相应的分组中
            unset($item['prescription_id']);
            $result[$key][] = $item;

            return $result;
        }, []);
        return message("操作成功", true, $examp);
    }

    /**
     * 提交答案
     */
    public function subAnswer()
    {
        $params = input('post.');
        $userId = $this->request->user_id;
        $rule = [
            'problem_id|题目编号' => 'require',
            'exam_id|考试编号' => 'require',
            'answer|答案' => 'require',
        ];
        $validate = Validate::rule($rule);
        if (!$validate->check($params)) {
            return message($validate->getError(), false);
        }
        $exam_problem_info = Db::name('exam_problem')
            ->where('id', $params['problem_id'])
            ->field('right_key,score')
            ->find();
        if (empty($exam_problem_info)) {
            return message('该题目不存在', false);
        }
        $score = $this->sumScore(strtoupper($params['answer']), $exam_problem_info);
        $isExitsId = Db::name('exam_user_answer')
            ->where('problem_id', $params['problem_id'])
            ->where('exam_id', $params['exam_id'])
            ->value('id');
        if (empty($isExitsId)) {
            $data = [
                'exam_id' => $params['exam_id'],
                'problem_id' => $params['problem_id'],
                'user_id' => $userId,
                'score' => $score,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ];
            Db::name('exam_user_answer')->insert($data);
        } else {
//            TODO 分数待算
            $updata = [
                'score' => $score,
            ];
            Db::name('exam_user_answer')
                ->where('id', $isExitsId)
                ->update($updata);
        }
        return message('提交成功', true);
    }

    /**
     * @param $answer
     * @param $exam_problem_info
     * @return int
     * 计算该题得分情况
     */
    public function sumScore($answer, $exam_problem_info)
    {
        $right_key = $exam_problem_info['right_key'];
        $right_key_array = str_split($right_key);
        $answer_array = str_split($answer);
        if ($answer == $right_key) {
            $score = $exam_problem_info['score'];
            return $score;
        }
        foreach ($answer_array as $answeritem) {
            if (!in_array($answeritem, $right_key_array)) {
                return $score = 0;
            } else {
                return $score = 3;
            }
        }
    }

    /**
     * 提交考试成绩
     */
    public function subExam()
    {
        $params = input('post.');
        $userId = $this->request->user_id;
        $rule = [
            'exam_id|考试编号' => 'require',
            'exam_log_id|考试记录编号' => 'require',
            'usetime|考试用时' => 'require',
        ];
        $validate = Validate::rule($rule);
        if (!$validate->check($params)) {
            return message($validate->getError(), false);
        }
        $allscore = Db::name('exam_user_answer')
            ->where('exam_log_id', $params['exam_log_id'])
            ->sum('score');
        $data = [
            'score' => $allscore,
            'status' => 1,
            'usetime' => $params['usetime'],
        ];
        Db::name('exam_log')
            ->where('exam_id', $params['exam_id'])
            ->where('user_id', $userId)
            ->update($data);
        return message('提交成功', true);
    }
}